package com.allenkerr.web;

import com.allenkerr.model.Book;
import com.allenkerr.service.BookService;
import com.allenkerr.vo.BookSearchParams;
import com.allenkerr.vo.Result;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by 小柯 on 17/9/7.
 */
@RestController
@RequestMapping(value = "/books", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class BookController {

  @Autowired
  private BookService bookService;

  @GetMapping("/init")
  public Result init() {

    GeoPoint geoPoint = new GeoPoint(39.98, 105.87);
    String geoPointStr = "39.98,105.87";

    Book book1 = new Book("1001", "Elasticsearch Basics", "Rambabu Posa", "2017-9-1", geoPoint, geoPointStr);
    Book book2 = new Book("1002", "Apache Lucene Basics", "Rambabu Posa", "2017-9-1", geoPoint, geoPointStr);
    Book book3 = new Book("1003", "Apache Solr Basics", "Rambabu Posa", "2017-9-1", geoPoint, geoPointStr);
    Book book4 = new Book("1004", "Spring Data + ElasticSearch", "Rambabu Posa", "2017-9-1", geoPoint, geoPointStr);
    Book book5 = new Book("1005", "Spring Boot + MongoDB", "Mkyong", "2017-9-1", geoPoint, geoPointStr);
    Book book6 = new Book("1006", "西游记", "吴承恩", "1054-5-4", geoPoint, geoPointStr);
    Book book7 = new Book("1007", "钢铁是怎样炼成的", "保尔 柯察金", "1984-4-7", geoPoint, geoPointStr);

    List<Book> bookList = Arrays.asList(book1, book2, book3, book4, book5, book6, book7);

    Iterator<Book> savedBooks = bookService.init(bookList);
    return Result.success(savedBooks);
  }

//    @GetMapping("")
//    public Result listBooks(@RequestParam(required = false) String title) {
//        if (StringUtils.isNotBlank(title)) {
//            Map<String, List<Book>> bookListMap = bookService.findByTitleIsLike(title.trim());
//            return Result.success(bookListMap);
//        }
//
//        Iterable<Book> bookIterable = bookService.findAll();
//        AggregatedPage page = (AggregatedPage) bookIterable;
//        return Result.success(page.getContent());
//    }

  @GetMapping("")
  public Result listBooks(@RequestParam Map<String, String> map) {
    BookSearchParams searchParams = new BookSearchParams(map);
    List<Book> bookList = bookService.listBooks(searchParams);
    return Result.success(bookList);
  }

}
